﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VisionFrame.Base;

namespace LogicControl
{
    public class AddNodeModel : NodeModelBase
    {
        public AddNodeModel()
        {
            this.Arguments.Add(new VisionFrame.Base.Models.NodeArgModel
            {
                ArgName = "加数",
                ArgType = "Any",
                Direction = "输入"
            });
            this.Arguments.Add(new VisionFrame.Base.Models.NodeArgModel
            {
                ArgName = "累加值",
                ArgType = "Any",
                Direction = "输入",
                ValueMode = 1
            });
            this.Arguments.Add(new VisionFrame.Base.Models.NodeArgModel
            {
                ArgName = "结果",
                ArgType = "Any",
                Direction = "输出"
            });
        }

        public override void Execute(IFlowContext flowContext)
        {
            if (this.Arguments[0].ArgValue == null)
                throw new Exception("参数未配置");
            if (this.Arguments[1].ArgValue == null)
                throw new Exception("参数未配置");
            if (this.Arguments[2].ArgValue == null)
                throw new Exception("参数未配置");


            // 手动输入/下拉选择的差别处理
            string org_value = this.Arguments[0].ArgValue.ToString();
            if (this.Arguments[0].ValueMode == 0)
            {
                var am = flowContext.ArgumentList
                   .FirstOrDefault(a => a.ArgName == this.Arguments[0].ArgValue.ToString());
                if (am != null)
                    org_value = (am.Value ?? 0).ToString();
            }
            // 累加值 
            string add_value = this.Arguments[1].ArgValue.ToString();
            if (this.Arguments[1].ValueMode == 0)
            {
                var am = flowContext.ArgumentList
                   .FirstOrDefault(a => a.ArgName == this.Arguments[1].ArgValue.ToString());
                if (am != null)
                    add_value = (am.Value ?? 0).ToString();
            }

            // 加法结果 
            string compare = org_value + "+" + add_value;
            object result = new DataTable().Compute(compare, "");

            var rm = flowContext.ArgumentList
                   .FirstOrDefault(a => a.ArgName == this.Arguments[2].ArgValue.ToString());
            if (rm != null)
                rm.Value = result;
        }
    }
}
